/**
 * 
 */
package array.passed;

/**
 * @author xyyi
 *
 */
public class RemoveDuplicatesfromSortedArrayII {

	/**
	Follow up for "Remove Duplicates":
	What if duplicates are allowed at most twice?

	For example,
	Given sorted array A = [1,1,1,2,2,3],

	Your function should return length = 5, and A is now [1,1,2,2,3].
	 */
	public int removeDuplicates(int[] A) {
		if (A == null || A.length == 0)
			return 0;

		int write = 0, read = 1;
		// second visited to check if the number is appeared 2nd time
		for (boolean visited2nd = false; read < A.length; read++) {
			if (A[read] == A[write]) {
				if (!visited2nd) {
					A[++write] = A[read];
					visited2nd = true;
				}
			} else {
				A[++write] = A[read];
				visited2nd = false;
			}
		}

		return write + 1;
	}

	/**
	 * 
	 */
	public RemoveDuplicatesfromSortedArrayII() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
